package com.hsw.bledemo.review.kotlin

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @author: HSW
 * @data: 2024/7/5
 * @desc: 解决livedata 数据粘性问题/数据回溯
 */

/**
 * 单个注册的情况
 */
class SingleLiveEvent<T>: MutableLiveData<T>() {

    private val mPending = AtomicBoolean(false)

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner) {
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(it)
            }
        }
    }


    override fun setValue(value: T) {
        mPending.set(true)
        super.setValue(value)
    }
}

/**
 * 多个注册的情况
 */
class MoreLiveEvent<T>: MutableLiveData<T>() {

    private val map = mutableMapOf<String, AtomicBoolean>()

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        val className = owner.javaClass.name
        if (!map.containsKey(className)) {
            map[owner.javaClass.name] = AtomicBoolean(false)
        }
        super.observe(owner) {
            if (map[owner.javaClass.name]?.compareAndSet(true, false) == true) {
                observer.onChanged(it)
            }
        }
    }

    override fun setValue(value: T) {
        super.setValue(value)
    }

    fun setValue(owner: LifecycleOwner, value: T) {
        map[owner.javaClass.name]?.set(true)
        setValue(value)
    }
}